package com.wiloon.androidx.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.wiloon.androidx.entity.Bar;
import com.wiloon.androidx.entity.Foo;

import java.sql.SQLException;

/**
 * Created by wiloon on 7/25/14.
 */

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String databaseName = "androidx.db";
    private static final int databaseVersion = 1;

    public DatabaseHelper(Context context) {
        super(context, databaseName, null, databaseVersion);
    }

    private RuntimeExceptionDao<Foo, Long> fooDao = null;
    private Dao<Bar, Long> barDao = null;

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            Log.d(DatabaseHelper.class.getName(), "create database start.");
            TableUtils.createTable(connectionSource, Foo.class);
            TableUtils.createTable(connectionSource, Bar.class);
            Log.d(DatabaseHelper.class.getName(), "create database done.");
        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "create database failed.", e);
        }
    }


    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i2) {
        try {
            TableUtils.dropTable(connectionSource, Foo.class, true);
            TableUtils.dropTable(connectionSource, Bar.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {

        }
    }

    @Override
    public void close() {
        super.close();
    }

    public RuntimeExceptionDao<Foo, Long> getFooDao() {
        if (fooDao == null) {
            fooDao = getRuntimeExceptionDao(Foo.class);
        }
        return fooDao;
    }

    public Dao<Bar, Long> getBarDao() throws SQLException {
        if (barDao == null) {
            barDao = getDao(Bar.class);
        }
        return barDao;
    }
}

